package com.yyds.yygh.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.StringUtils;
import com.yyds.yygh.msm.service.MsmService;
import com.yyds.yygh.msm.utils.ConstantPropertiesUtils;
import com.yyds.yygh.vo.msm.MsmVo;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {

    @Override
    public boolean send(String phone, String code) {
        //判断手机号是否为空
        if (StringUtils.isNullOrEmpty(phone)){
            return false;
        }
        //整合榛子云短信服务
        String apiUrl = ConstantPropertiesUtils.API_URL;
        String appId = ConstantPropertiesUtils.APP_ID;
        String appSecret = ConstantPropertiesUtils.APP_SECRET;
        String templatedId = ConstantPropertiesUtils.TEMPLATED_ID;
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phone);
        params.put("templateId", templatedId);
        String[] templateParams = new String[2];
        //验证码
        templateParams[0] = code;
        //分钟数
        templateParams[1] = "2";
        params.put("templateParams", templateParams);
        try {
            String result = client.send(params);
            Map map = JSONObject.parseObject(result, Map.class);
            return map.get("data").toString().equals("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean send(MsmVo msmVo) {
        if (!StringUtils.isNullOrEmpty(msmVo.getPhone())){
            boolean send = this.send(msmVo.getPhone(), msmVo.getParam());
            return send;
        }
        return false;
    }

    public boolean send(String phone,Map<String,Object> param){
        //判断手机是否为空
        if (StringUtils.isNullOrEmpty(phone)){
            return false;
        }
        //整合榛子云短信服务
        String apiUrl = ConstantPropertiesUtils.API_URL;
        String appId = ConstantPropertiesUtils.APP_ID;
        String appSecret = ConstantPropertiesUtils.APP_SECRET;
        String templateId ="8319";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phone);
        params.put("templateId", templateId);
        String[] templateParams = new String[1];
        templateParams[0] = JSONObject.toJSONString(param);
        params.put("templateParams", templateParams);
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        try {
            String result = client.send(params);
            Map map = JSONObject.parseObject(result, Map.class);
            return map.get("data").toString().equals("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  false;
    }

}
